package com.visionet.school.app.web.service.member;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.visionet.school.app.web.common.utilities.props.PropsKeys;
import com.visionet.school.app.web.common.utilities.props.PropsUtil;
import com.visionet.school.app.web.common.utils.DateUtils;
import com.visionet.school.app.web.common.utils.PageUtils;
import com.visionet.school.app.web.common.web.WebContextFactory;
import com.visionet.school.app.web.entity.assess.Assess;
import com.visionet.school.app.web.entity.enums.MemberFileType;
import com.visionet.school.app.web.entity.enums.MemberType;
import com.visionet.school.app.web.entity.file.FileClass;
import com.visionet.school.app.web.entity.file.vo.FileVo;
import com.visionet.school.app.web.entity.member.*;
import com.visionet.school.app.web.entity.member.vo.AsAndMeVo;
import com.visionet.school.app.web.entity.member.vo.AssessVo;
import com.visionet.school.app.web.entity.member.vo.MemberAssessVo;
import com.visionet.school.app.web.entity.member.vo.MemberExtendInfoVo;
import com.visionet.school.app.web.entity.tclass.SchoolClass;
import com.visionet.school.app.web.entity.user.User;
import com.visionet.school.app.web.entity.vo.LoginAccountVo;
import com.visionet.school.app.web.entity.vo.MemberVo;
import com.visionet.school.app.web.repository.member.*;
import com.visionet.school.app.web.repository.tclass.SchoolClassRepository;
import com.visionet.school.app.web.service.file.FileClassService;
import com.visionet.school.app.web.service.user.UserService;
import com.visionet.school.app.web.service.wechat.WechatService;
import com.visionet.school.app.web.task.DownLoadFileTask;
import com.visionet.school.app.web.wechat.utils.MemberUtil;
import com.visionet.school.app.web.wechat.vo.MainVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import sun.applet.Main;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

/**
 * Created by hxpeng on 2017/3/3.
 */
@Service
public class MemberService {

    private static final Logger logger = LoggerFactory.getLogger(MemberService.class);

    @Resource
    private SchoolClassRepository schoolClassRepository;

    @Resource
    private MemberRepository memberRepository;

    @Resource
    private MemberRelRepository memberRelRepository;

    @Resource
    private MemberClassRepository memberClassRepository;

    @Resource
    private MemberExtendInfoRepository memberExtendInfoRepository;

    @Resource
    private UserService userService;

    @Resource
    private FileClassService fileClassService;

    @Resource
    private MemberFileRepository memberFileRepository;

    @Resource
    private WechatService wechatService;

    @Resource
    private AssessRepository assessRepository;

    int minsize = 3;

    public Member findOneById(String memberId){return memberRepository.findOne(memberId);}

    public LoginAccountVo createParent(MemberVo memberVo){
        Member member = new Member();
        BeanUtils.copyProperties(memberVo,member);
        member.setMemberType(MemberType.PARENT.toKey());
        member.setIsDeleted("0");
        memberRepository.save(member);

        LoginAccountVo loginAccountVo = WebContextFactory.getWebContext().getLoginAccountVo();
        User user = userService.findOneByOpenId(loginAccountVo.getOpenId());
        if(user == null){
            logger.error("未找到登陆账号");
            throw new RuntimeException("创建失败！");
        }
        user.setMemberId(member.getId());
        user.setParentGender(memberVo.getMemberRelType());
        userService.save(user);
        loginAccountVo.setMemberId(member.getId());
        loginAccountVo.setMemberName(member.getMemberName());
        loginAccountVo.setMemberType(MemberType.PARENT.toKey());
        loginAccountVo.setParentGender(memberVo.getMemberRelType());

        //向微信发送请求，给该用户添上家长的标签
        List<String> opendIds = new ArrayList<>();
        opendIds.add(loginAccountVo.getOpenId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("openid_list",opendIds);
        jsonObject.put("tagid","101");
        logger.info("提交参数jsonObject：" + jsonObject.toJSONString());
        String resultJson = MemberUtil.addTagToMembers(jsonObject.toJSONString());
        logger.info("返回消息：resultJson" + resultJson);
        JSONObject resultJsonObj = JSONObject.parseObject(resultJson);
        if(StringUtils.isNotBlank(resultJsonObj.getString("errcode")) && resultJsonObj.getString("errcode").equals("0")){
            logger.info("成功，用户id为：" + member.getId() + "加上家长标签！");
        }else{
            logger.info("失败，用户id为：" + member.getId() + "添加家长标签失败：" + resultJsonObj.getString("errmsg"));
        }

        return loginAccountVo;
    }

    public void studentBindParent(String studentId){
        Member student = memberRepository.findOne(studentId);
        if(student == null){
            throw new RuntimeException("未找到改宝宝！");
        }
        LoginAccountVo loginAccountVo = WebContextFactory.getWebContext().getLoginAccountVo();
        User user = userService.findOneByOpenId(loginAccountVo.getOpenId());
        if(user == null){
            logger.error("未找到登陆账号");
            throw new RuntimeException("绑定失败，请联系管理员！");
        }
        MemberRel entity = memberRelRepository.findOneBymidAndsid(loginAccountVo.getMemberId(),student.getId());
        if(entity != null){
            throw new RuntimeException("你已经和这位宝宝绑定过关系了！");
        }
        MemberRel memberRel  = new MemberRel();
        memberRel.setMemberId(student.getId());
        memberRel.setRelMemberId(user.getMemberId());
        memberRel.setRelType(user.getParentGender());
        memberRel.setIsDeleted("0");
        memberRelRepository.save(memberRel);
    }

    public List<Member> findStudentByParentId(String memberId){
        List<Member> studentInfoList =new ArrayList<>();
        List<MemberRel> memberRelList=memberRelRepository.findAllStudentByParent(memberId);
        if(memberRelList!=null){
            for(MemberRel memberRel : memberRelList){
                Member student = memberRepository.findOne(memberRel.getMemberId());
                if(student != null){
                    studentInfoList.add(student);
                }
            }
            return studentInfoList;
        }else{
            return null;
            //        return memberRelRepository.findStudentIdByParent(memberId);
        }
    }

    public Member findStudentByNumberAndName(MemberVo memberVo){
        return memberRepository.findStudentByNumberAndName(memberVo.getStudentNumber(),memberVo.getMemberName());
    }

    public MemberVo getMemberInfo(String id){
        MemberVo memberVo = new MemberVo();
        Member member = memberRepository.getMemberInfo(id);
        if(member != null){
            MemberExtendInfo memberExtendInfo = memberExtendInfoRepository.getMemberExtendInfo(member.getId());
            if(memberExtendInfo != null){
                BeanUtils.copyProperties(memberExtendInfo,memberVo);
            }
            BeanUtils.copyProperties(member,memberVo);
            return memberVo;
        }
        return null;
    }

    public Member pcSaveMemberInfo(MemberVo memberVo){
        try {
            Member member = new Member();
            MemberExtendInfo memberExtendInfo = new MemberExtendInfo();
            MemberExtendInfoVo memberExtendInfoVo = new MemberExtendInfoVo();
            if(StringUtils.isNotBlank(memberVo.getId())){
                member = memberRepository.findOne(memberVo.getId());
                memberExtendInfo = memberExtendInfoRepository.getMemberExtendInfo(member.getId());
            }
            BeanUtils.copyProperties(memberVo,member);
            BeanUtils.copyProperties(memberVo,memberExtendInfoVo);//暂时用此方法区分赋值两个member和memberExtendInfo重复的字段
            BeanUtils.copyProperties(memberExtendInfoVo,memberExtendInfo);
            member.setIsDeleted("0");
            memberExtendInfo.setIsDeleted("0");
            memberRepository.save(member);
            memberExtendInfoRepository.save(memberExtendInfo);
            return member;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }

    }

    /**
     * 微信端修改家长信息。
     * @param memberVo
     * @return
     */
    public Member saveMemberInfo(MemberVo memberVo){
        Member member = memberRepository.findOne(memberVo.getId());
        if(member == null){
            return null;
        }
        BeanUtils.copyProperties(memberVo,member);
        return memberRepository.save(member);
    }

    public Map<String, Object> getMemberPage(MemberVo memberVo, String sortType){
        Page<MemberVo> objPage = memberRepository.findMemberPage(memberVo, sortType);
        return PageUtils.getPageMap(objPage);
    }

    /**
     * 事务隔离为READ_COMMITTED
     * 查询出来的count 为未更新的数据，这里给手动-1
     * @param id
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void deleteStudent(String id){
        try{
            MemberClass memberClass = memberClassRepository.findOne(id);
            memberClass.setIsDeleted("1");
            memberClassRepository.save(memberClass);
            SchoolClass schoolClass = schoolClassRepository.findOneById(memberClass.getClassId());
            int count = memberClassRepository.countMemberClass(memberClass.getClassId());
            schoolClass.setClassNumber(count > 1 ? count -1 : 0);
            schoolClassRepository.save(schoolClass);
        }catch (Exception e){
            logger.error("删除学生失败！");
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    public Map<String, Object> queryStudent(MemberVo memberVo){
        Page<MemberVo> objPage = memberRepository.queryStudentPage(memberVo);
        return PageUtils.getPageMap(objPage);
    }

    public List<MemberVo> queryTeacher(MemberVo memberVo){
        return memberRepository.queryTeacher("%"+memberVo.getMemberName()+"%",memberVo.getMemberType());
    }

    /**
     * 事务隔离为READ_COMMITTED
     * 查询出来的count 为未更新的数据，这里给手动+1
     * @param memberVo
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void insertStudentClass(MemberVo memberVo){
//        MemberClass memberClass;
//        if(StringUtils.isNotBlank(memberVo.getId())){
//            memberClass = new MemberClass();
//            memberClass.setMemberId(memberVo.getId());
//            memberClass.setClassId(memberVo.getClassId());
//            memberClass.setMemberType(MemberType.STUDENT.toKey());
//            memberClass.setIsDeleted("0");
//            memberClassRepository.save(memberClass);
//        }
//        if(StringUtils.isNotBlank(memberVo.getMemberClassId())){
//            memberClass = memberClassRepository.findOne(memberVo.getMemberClassId());
//            memberClass.setClassId(memberVo.getClassId());
//            memberClassRepository.save(memberClass);
//        }
        List<MemberClass> memberClasses = memberClassRepository.findByMemberIdAndType(memberVo.getMemberId(),MemberType.STUDENT.toKey());
        if(null != memberClasses && memberClasses.size() > 0){
            throw new RuntimeException("学生已被添加进其他班级！");
        }
        MemberClass memberClass = new MemberClass();
        memberClass.setMemberId(memberVo.getMemberId());
        memberClass.setClassId(memberVo.getClassId());
        memberClass.setMemberType(MemberType.STUDENT.toKey());
        memberClass.setIsDeleted("0");
        memberClassRepository.save(memberClass);

        SchoolClass schoolClass = schoolClassRepository.findOneById(memberVo.getClassId());
        int count = memberClassRepository.countMemberClassByType(memberVo.getClassId(),MemberType.STUDENT.toKey());
        schoolClass.setClassNumber(count);
        schoolClassRepository.save(schoolClass);
    }


    /**
     * 微信绑定成员，并更新当前会话中的角色信息
     * @param memberVo
     */
    public LoginAccountVo bindWeChatInfo(MemberVo memberVo){
        try {
            String memberType = memberVo.getMemberType();
            String openId = memberVo.getOpenId();
            String memberPhone = "";
            String memberId = "";

            User user = userService.findOneByOpenId(openId);
            if(user == null){
                throw new NullPointerException("找不到该登陆账号！");
            }

            if(memberType.equals(MemberType.TEACHER.toKey())){
                Member member = memberRepository.findOneByNameAndPhone(memberVo.getMemberName(),memberVo.getMemberPhone());
                if(member == null){
                    throw new NullPointerException("找不到这个老师，请核对输入信息");
                }
                SchoolClass schoolClass = schoolClassRepository.findOneByClassName(memberVo.getClassName());
                if(schoolClass == null){
                    throw new NullPointerException("找不到这个班级，请核对输入信息");
                }
                //绑定教师与班级关系
                MemberClass memberClass = memberClassRepository.findOneByMemberId(member.getId());
                if(memberClass == null){
                    throw new NullPointerException("教师未绑定班级！");
                }
                memberPhone = member.getMemberPhone();
                memberId = member.getId();

                //向微信发送请求，给该用户添上教师的标签
                List<String> opendIds = new ArrayList<>();
                opendIds.add(openId);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("openid_list",opendIds);
                jsonObject.put("tagid","100");
                logger.info("提交参数jsonObject：" + jsonObject.toJSONString());
                String resultJson = MemberUtil.addTagToMembers(jsonObject.toJSONString());
                logger.info("返回消息：resultJson" + resultJson);
                JSONObject resultJsonObj = JSONObject.parseObject(resultJson);
                if(StringUtils.isNotBlank(resultJsonObj.getString("errcode")) && resultJsonObj.getString("errcode").equals("0")){
                    logger.info("成功，用户id为：" + member.getId() + "加上教师标签！");
                }else{
                    logger.info("失败，用户id为：" + member.getId() + "添加教室标签失败：" + resultJsonObj.getString("errmsg"));
                }
            }else if(memberType.equals(MemberType.PARENT.toKey())){
                //判断被绑定学生是否存在
                Member student = memberRepository.findStudentByNumberAndName(memberVo.getStudentNumber(), memberVo.getStudentName());
                if(student == null){
                    throw new NullPointerException("找不到这个学生，请核对输入信息");
                }

                //保存家长基础信息
                Member member = new Member();
                member.setMemberName(memberVo.getMemberName());
                member.setMemberPhone(memberVo.getMemberPhone());
                member.setMemberType(MemberType.PARENT.toKey());
                member.setAvatarPath(user.getProfile());
                member.setMemberSex(user.getSex());
                member.setIsDeleted("0");
                memberRepository.save(member);

                //保存关系表
                MemberRel memberRel = new MemberRel();
                memberRel.setMemberId(student.getId());
                memberRel.setRelMemberId(member.getId());
                memberRel.setRelType(memberVo.getMemberRelType());
                memberRel.setIsDeleted("0");
                memberRelRepository.save(memberRel);

                memberPhone = member.getMemberPhone();
                memberId = member.getId();
            }
            logger.info("查找登陆账号："  + user.getLoginName());
            user.setMobile(memberPhone);
            user.setMemberId(memberId);
            user = userService.save(user);
            logger.info("更新user:" + user.toString());
            return wechatService.getLoginAccountVo(user);
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * 获取微信图片serverID, 多线程获取保存
     * @param serverIds
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public List<FileVo> downLoadWechatImg(List<String> serverIds) {
        //设置线程池，最多九个
        try {
            List<FileVo> resultList = new ArrayList<>();
            List<Future<FileClass>> tasks = new ArrayList();
            ExecutorService executor = Executors.newFixedThreadPool(9);

            LoginAccountVo loginAccountVo = WebContextFactory.getWebContext().getLoginAccountVo();
            String memberId = loginAccountVo.getMemberId();
            StringBuffer stringBuffer = new StringBuffer(PropsUtil.getProperty(PropsKeys.SERVER_IMG_PATH));
            stringBuffer.append("/").append(memberId);
            stringBuffer.append("_").append(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

            for(String s : serverIds){
                DownLoadFileTask downLoadFileTask = new DownLoadFileTask(s,stringBuffer.toString());
                tasks.add(executor.submit(downLoadFileTask));
            }
            executor.shutdown();
            logger.info("===================================================");
            //当前线程阻塞，直到所有已提交的任务（包括正在跑的和队列中等待的）执行完或者等超时时间到
            //或者线程被中断，抛出InterruptedException
            executor.awaitTermination(1, TimeUnit.SECONDS);
            //获取所有的callable的返回结果，保存
            for (Future<FileClass> f : tasks) {
                FileClass fileClass = f.get();
                fileClass = fileClassService.save(fileClass);
                MemberFile memberFile = new MemberFile();
                memberFile.setMemberFileType(MemberFileType.ALBUM.toKey());
                memberFile.setMemberId(memberId);
                memberFile.setFileId(fileClass.getId());
                memberFile.setIsDeleted("0");
                memberFileRepository.save(memberFile);

                //返回图片路径+media_Id,mediaId用来区分
                FileVo fileVo = new FileVo();
                fileVo.setFilePath(fileClass.getFilePath());
                fileVo.setThumbnail(fileClass.getThumbnail());
                fileVo.setMediaId(fileClass.getMediaId());
                resultList.add(fileVo);
            }
            logger.info("批量文件下载完毕！！！");
            return resultList;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("图片下载失败！");
        }
    }

    public List<MemberVo> getParentInfo(String studentId){
        if(StringUtils.isNoneBlank(studentId)){
            List<MemberVo> result = new ArrayList<>();
            List<MemberRel> list = memberRelRepository.findParentList(studentId);
            if(null != list){
                for(MemberRel memberRel : list){
                    Member member = memberRepository.findOne(memberRel.getRelMemberId());
                    MemberVo memberVo = new MemberVo();
                    BeanUtils.copyProperties(member,memberVo);
                    memberVo.setMemberRelType(memberRel.getRelType());
                    result.add(memberVo);
                }
                Member member = memberRepository.findOne(studentId);
                MemberVo memberVo = new MemberVo();
                BeanUtils.copyProperties(member,memberVo);
                result.add(memberVo);
                return result;
            }
        }
        return null;
    }


//    public void modify(MemberVo memberVo,String changeMemberName,String changeMemberPhone){
//        Member member;
//        member=memberRepository.findOneById(memberVo.getId());
//
//        try{
//            if(changeMemberName!=null){
//                member.setMemberName(changeMemberName);
//            }
//            if(changeMemberPhone!=null){
//                member.setMemberPhone(changeMemberPhone);
//            }
////            member.setMemberType(MemberType.PARENT.toKey());
//            memberRepository.save(member);
//        }catch (Exception e){
//            throw new RuntimeException("更改个人信息失败："+e.getMessage());
//        }
//    }

    public List<MemberAssessVo> getMemberList(String id) {
        return memberRepository.getMemberList(id.trim());
    }

    public AsAndMeVo getAssessById(String memberId) {
        AsAndMeVo entitys = new AsAndMeVo();
//        AsAndMeVo vo = new AsAndMeVo();
        if (null != memberId) {
            AsAndMeVo entity = memberRepository.getAssessById(memberId.trim());
            if (entity == null) {
                Member member = memberRepository.findOneById(memberId.trim());
                if (member != null) {
                    entitys.setMemberName(member.getMemberName());
                    entitys.setAvatarPath(member.getAvatarPath());
                    entitys.setMemberSex(member.getMemberSex());
                    entitys.setMemberId(member.getId());
                }
            } else {
                entitys = entity;
            }
        }
        return entitys;
    }

    public List<AsAndMeVo> findAssess(String classId) {
        return memberRepository.findAssess(classId.trim());
    }

    public String saveAssess(AssessVo assessVo) {
        String msg = "";
        try {
            Assess assess = assessCopy(assessVo);
            assessRepository.save(assess);
            msg = "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }

    public Assess assessCopy(AssessVo assessVo) {
        Assess assess = new Assess();
        assess.setAssessStatus("1");
        assess.setSleep(assessVo.getSleep());
        assess.setSinceReason(assessVo.getSinceReason());
        assess.setOperation(assessVo.getOperation());
        assess.setCommunication(assessVo.getCommunication());
        assess.setEmotion(assessVo.getEmotion());
        assess.setHabit(assessVo.getHabit());
        assess.setHealthy(assessVo.getHealthy());
        assess.setHygiene(assessVo.getHygiene());
        assess.setMessage(assessVo.getMessage());
        assess.setTheMeal(assessVo.getTheMeal());
        assess.setMemberId(assessVo.getId());//assessVo.getId的是member的ID
        Date d = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        assess.setStartDate(format.format(d));
        assess.setCreateBy("16BFD02EB985735E351C6B89A19CA3EE");
//        if (assessVo.getId() != null) {
//            assess.setId(assessVo.getId());
//        }
        return assess;
    }
    public Map<String, Object> findAssessReport(String memberId) {
        HashMap<String, Object> map = new HashMap<>();
        Date date = new Date();
        SimpleDateFormat s = new SimpleDateFormat("E");
        String e = s.format(date);
        if ("星期六".equals(e) || "星期日".equals(e)) {
            String startDate = DateUtils.getCurrentMonday();//获取当前周一的开始日期
            String endDate = DateUtils.getPreviousSunday();//获取当前周五的结束日期
            Map<String, Object[]> report = memberRepository.findAssessReport(startDate, endDate, memberId);
            List<AssessVo> assessVos = memberRepository.findAssessReportFraction(startDate, endDate, memberId);
            int i = memberRepository.findAssessReportFractionSize(startDate, endDate, memberId);
            for (AssessVo av : assessVos) {
                av.setSumTheMeal((av.getSumTheMeal() *20)/i);
                av.setSumSleep((av.getSumSleep()*20)/i);
                av.setSumSinceReason((av.getSumSinceReason()*20)/i);
                av.setSumEmotion((av.getSumEmotion()*20)/i);
                av.setSumHabit((av.getSumHabit()*20)/i);
                av.setSumCommunication((av.getSumCommunication()*20)/i);
                av.setSumOperation((av.getSumOperation()*20)/i);
                av.setSumHealthy((av.getSumHealthy()*20)/i);
                av.setSumHygiene((av.getSumHygiene()*20)/i);
            }
            int size = 0;
            for (String in : report.keySet()) {
                Object[] obj = report.get(in);
                if (obj.length != 0) {
                    size += 1;
                }
            }
            if (size == 0) {
                minsize-=1;
                if (minsize != 0) {
                    return loopDate(memberId,7,9);
                }
//                return loopDate(memberId,7,9);
            }
//            map.put("attribute",memberRepository.findAssessReport(startDate, endDate, memberId));
            StringBuffer sf = new StringBuffer();
            sf.append(String.valueOf(startDate));
            sf.append("至");
            sf.append(String.valueOf(endDate));
//            sf.append("(本周)");
            map.put("date",sf.toString());
            map.put("fraction",assessVos);
        } else {
            return loopDate(memberId,7,7);//7代表上周一时间，7代表上周五时间
        }
        return map;
    }

    public Map<String, Object> loopDate(String memberId, int dateStartSize, int dateEndSize) {
        SimpleDateFormat sa = new SimpleDateFormat("yyyy-MM-dd");
        String upperStartDate = sa.format(DateUtils.lastMonday(dateStartSize));//获取上周一开始日期
        String upperEndDate = sa.format(DateUtils.lastFirday(dateEndSize));//获取上周五开始日期
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object[]> report = memberRepository.findAssessReport(upperStartDate.trim(), upperEndDate.trim(), memberId.trim());
        List<AssessVo> assessVos = memberRepository.findAssessReportFraction(upperStartDate.trim(), upperEndDate.trim(), memberId.trim());
        int i = memberRepository.findAssessReportFractionSize(upperStartDate.trim(), upperEndDate.trim(), memberId.trim());
        for (AssessVo av : assessVos) {
            av.setSumTheMeal((av.getSumTheMeal() *20)/i);
            av.setSumSleep((av.getSumSleep()*20)/5);
            av.setSumSinceReason((av.getSumSinceReason()*20)/i);
            av.setSumEmotion((av.getSumEmotion()*20)/i);
            av.setSumHabit((av.getSumHabit()*20)/i);
            av.setSumCommunication((av.getSumCommunication()*20)/i);
            av.setSumOperation((av.getSumOperation()*20)/i);
            av.setSumHealthy((av.getSumHealthy()*20)/i);
            av.setSumHygiene((av.getSumHygiene()*20)/i);
        }
        int size = 0;
        for (String in : report.keySet()) {
            Object[] obj = report.get(in);
            if (obj.length != 0) {
                size += 1;
            }
        }
        if (size == 0) {
            if (minsize == 0) {
                minsize+=3;
            }
            minsize-=1;
            if (minsize != 0) {
                return loopDate(memberId,dateStartSize +7 ,dateEndSize + 7);
            }

        } else {
            if (size == 0) {
                map.put("msg","null");
            } else {
                map.put("msg","success");
            }
            StringBuffer sf = new StringBuffer();
            sf.append(String.valueOf(upperStartDate));
            sf.append("至");
            sf.append(String.valueOf(upperEndDate));
            map.put("date",sf.toString());
            map.put("attribute",report);
            map.put("startDate", dateStartSize);
            map.put("endDate",dateEndSize);
            map.put("fraction",assessVos);
        }
        return map;
    }

    public Map<String, Object> findReportMonthYear(String memberId, String dataType, int dateStartSize, int dateEndSize) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        if ("month".equals(dataType)) {
            //0为当前月的起止时间
            String startDate = DateUtils.getBeforeFirstMonthdate(dateStartSize);//上个月开始时间
            String endDate = DateUtils.getBeforeLastMonthdate(dateEndSize);//上个月结束时间
            Map<String, Object[]> report = memberRepository.findAssessReport(startDate.trim(), endDate.trim(), memberId.trim());
            List<AssessVo> assessVos = memberRepository.findAssessReportFraction(startDate.trim(), endDate.trim(), memberId.trim());
            int i = memberRepository.findAssessReportFractionSize(startDate.trim(), endDate.trim(), memberId.trim());
            for (AssessVo av : assessVos) {
                av.setSumTheMeal((av.getSumTheMeal() *20)/i);
                av.setSumSleep((av.getSumSleep()*20)/5);
                av.setSumSinceReason((av.getSumSinceReason()*20)/i);
                av.setSumEmotion((av.getSumEmotion()*20)/i);
                av.setSumHabit((av.getSumHabit()*20)/i);
                av.setSumCommunication((av.getSumCommunication()*20)/i);
                av.setSumOperation((av.getSumOperation()*20)/i);
                av.setSumHealthy((av.getSumHealthy()*20)/i);
                av.setSumHygiene((av.getSumHygiene()*20)/i);
            }
            int size = 0;
            for (String in : report.keySet()) {
                Object[] obj = report.get(in);
                if (obj.length != 0) {
                    size += 1;
                }
            }
            if (size == 0) {
                if (minsize == 0) {
                    minsize+=3;
                }
                minsize-=1;
                if (minsize != 0) {
                    return findReportMonthYear(memberId,"month",dateStartSize+1,dateEndSize + 1);
                }

            } else {
                if (size == 0) {
                    map.put("msg","null");
                } else {
                    map.put("msg","success");
                }
                StringBuffer sf = new StringBuffer();
                sf.append(String.valueOf(startDate));
                sf.append("至");
                sf.append(String.valueOf(endDate));
                map.put("date",sf.toString());
                map.put("attribute",report);
                map.put("startDate", dateStartSize);
                map.put("endDate",dateEndSize);
                map.put("dateTypes","month");
                map.put("fraction",assessVos);
            }


        } else {
            String startYear = DateUtils.getCurrentYearStartTime();
            String endYear = DateUtils.getCurrentYearEndTime();
            Map<String, Object[]> report = memberRepository.findAssessReport(startYear.trim(), endYear.trim(), memberId.trim());
            List<AssessVo> assessVos = memberRepository.findAssessReportFraction(startYear.trim(), endYear.trim(), memberId.trim());
            int i = memberRepository.findAssessReportFractionSize(startYear.trim(), endYear.trim(), memberId.trim());
            for (AssessVo av : assessVos) {
                av.setSumTheMeal((av.getSumTheMeal() *20)/i);
                av.setSumSleep((av.getSumSleep()*20)/5);
                av.setSumSinceReason((av.getSumSinceReason()*20)/i);
                av.setSumEmotion((av.getSumEmotion()*20)/i);
                av.setSumHabit((av.getSumHabit()*20)/i);
                av.setSumCommunication((av.getSumCommunication()*20)/i);
                av.setSumOperation((av.getSumOperation()*20)/i);
                av.setSumHealthy((av.getSumHealthy()*20)/i);
                av.setSumHygiene((av.getSumHygiene()*20)/i);
            }
            StringBuffer sf = new StringBuffer();
            sf.append(String.valueOf(startYear));
            sf.append("至");
            sf.append(String.valueOf(endYear));
//            sf.append("()");
            map.put("date",sf.toString());
            map.put("attribute",report);
            map.put("startDate", dateStartSize);
            map.put("endDate",dateEndSize);
            map.put("dateTypes","year");
            map.put("fraction",assessVos);
//            return map;
        }
        return map;
    }

    public String saveAssessTwo(AsAndMeVo asAndMeVo) {
        String msg = "";
        Assess assess = assessRepository.findOne(asAndMeVo.getAssessId());
        if (assess == null) {
            assess = new Assess();
        }
//        BeanUtils.copyProperties(asAndMeVo, assess);
        copyBeanAssess(asAndMeVo, assess);
        assessRepository.save(assess);
        msg = "success";
        return msg;
    }

    public void copyBeanAssess(AsAndMeVo asAndMeVo, Assess assess) {
        if (assess.getAssessStatus() == null) {
            assess.setAssessStatus("1");
        }
        if (assess.getStartDate() == null) {
            Date d = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            assess.setStartDate(dateFormat.format(d));
        }
        assess.setTheMeal(asAndMeVo.getTheMeal());
        assess.setMemberId(asAndMeVo.getMemberId());
        assess.setMessage(asAndMeVo.getMessage());
        assess.setHygiene(asAndMeVo.getHygiene());
        assess.setCommunication(asAndMeVo.getCommunication());
        assess.setEmotion(asAndMeVo.getEmotion());
        assess.setHabit(asAndMeVo.getHabit());
        assess.setHealthy(asAndMeVo.getHealthy());
        assess.setOperation(asAndMeVo.getOperation());
        assess.setSinceReason(asAndMeVo.getSinceReason());
        assess.setSleep(asAndMeVo.getSleep());
    }

}
